/*************************************************************************
	> File Name: Task.hpp
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/10/05 19:53
 ************************************************************************/

#pragma once

#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <sys/types.h>
#include "Tools/log.hpp"
#include <unistd.h>

const int BUF_SIZE = 1024;
#define SPACE " "
const int SPACE_SIZE = 1;

class Task
{
public:
    Task (const int sock, const uint16_t& port, const std::string& ip):_sock(sock), _port(port), _ip(ip)
    {}

    const void operator () () const
    {
        char buffer[BUF_SIZE];
        while (1) {
            memset(&buffer, 0, sizeof buffer);
            ssize_t s = read(_sock, buffer, sizeof buffer);
            if (s == 0) {
                logMessage(NORMAL, "client has shutdown.");
                break;
            } else if (s < 0) {
                logMessage(ERROR, "read error, client|%d|%s:%d", _sock, _ip.c_str(), _port);
                break;
            }
            std::string message = buffer;
            auto left = message.find(SPACE);
            auto right = message.rfind(SPACE);
            int leftNum = atoi(message.substr(0, left).c_str());
            int rightNum = atoi(message.substr(right + SPACE_SIZE).c_str());
            int res = leftNum + rightNum;
            std::string sendMessage = "res:" + std::to_string(res);
            write(_sock, sendMessage.c_str(), sendMessage.size());
        }
        close(_sock);
    }

    Task ()
    {}

private:
    std::string _ip;
    uint16_t _port;
    int _sock;
};
